#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <unordered_map>
#include "log.hpp"
#include "init.hpp"

Init init;

class Task
{
public:
    Task(int sockfd, const std::string &ip, const uint16_t port)
        : m_sockfd(sockfd), m_clientip(ip), m_clientport(port)
    {
    }

    void run()
    {
        char buffer[256];
        int n = read(m_sockfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;  // 输入的时候有可能是\r\n
            // std::cout << "client say# " << buffer << std::endl;
            // std::string echo_string = "tcpserver echo# ";
            // write(m_sockfd, echo_string.c_str(), echo_string.size());

            std::cout << "client key# " << buffer << std::endl;
            std::string echo_string = init.translation(buffer);

            // sleep(5);
            // close(m_sockfd);        
            // LOG(DEBUG, "close m_sockfd");

            // sleep(2);
            // 这里需要判断，有可能客户端建立好连接刚读完，客户端就关闭连接了。
            n = write(m_sockfd, echo_string.c_str(), echo_string.size());
            if(n < 0)
            {
                LOG(WARNING, "write error");
            }
        }
        else if (0 == n) // 如果客户端退出，read会读取到0
        {
            LOG(INFO, "client quit ...");
        }
        else
        {
            LOG(WARING, "read error ....");
        }
        close(m_sockfd);
    }

    void operator()()
    {
        run();
    }

    ~Task() {}

private:
    int m_sockfd;
    std::string m_clientip;
    uint16_t m_clientport;
};